/*
 * Created by JFormDesigner on Sat Jun 07 15:39:41 CST 2025
 */

package view;

import pojo.User;
import utils.JdbcConnectionUtils;

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Wwh
 */
public class Login extends JFrame {

    /**
     * 显示界面
     */
    public Login() {
        //初始化
        initComponents();
        //背景图
        background();
        JPanel panel1 = new JPanel();
        panel1.setOpaque(false);
        //关闭窗口
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //显示窗口
        this.setVisible(true);
    }

    /**
     * 加载背景图片
     */
    public void background(){
        ((JPanel)this.getContentPane()).setOpaque(false);
        ImageIcon img = new ImageIcon("D:\\Java\\allProject_week_17\\img\\login.jpg"); //添加图片
        JLabel background = new  JLabel(img);
        this.getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
        background.setBounds(0, 0, img.getIconWidth(), img.getIconHeight());

        // 5. 监听窗口resize，动态调整背景尺寸
        addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                background.setBounds(0, 0, getWidth(), getHeight());
            }
        });

    }

    /**
     * 登录
     *
     * @param e
     */
    private void loginButtonMouseClicked(MouseEvent e) {
        // TODO add your code here

        System.out.println("登录已被点击");

        List<User> users = new ArrayList<>();

        //赋值,用户名和密码
        String ur = this.usernameField.getText();
        String pass = this.passwordField.getText();

        //判断是否为空
        if(ur.isEmpty() || pass.isEmpty()){

            this.usernameField.setText("用户密码不能为空！");
            this.passwordField.setText("用户密码不能为空！");

            //TODO: 要求：将文本框中的提示信息停留一会在删除

            Timer timer = new Timer(3000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    usernameField.setText("");
                    passwordField.setText("");
                }
            });
            timer.setRepeats(false);
            timer.start();
            return;
        }

        //进行判断，来进行登录验证
        try {

            //获取一个连接
            Connection connection = JdbcConnectionUtils.getConnection();

            //创建PreparedStatement，并且执行sql语句
            String sql = "SELECT * FROM ww_user";
            Statement statement = connection.prepareStatement(sql);

            //4.执行sql语句
            ResultSet resultSet = statement.executeQuery(sql);

            //5.操作
            while(resultSet.next()){
                Long id = resultSet.getLong("id");
                String name = resultSet.getString("username");
                String pw = resultSet.getString("password");

                User user = new User(id,name,pw);
                users.add(user);

            }

            //6.关闭资源
            JdbcConnectionUtils.closeConnection(connection,statement,resultSet);

        }catch (Exception exception){
            exception.getMessage();
        }

        if(users.isEmpty() && users.size() == 0){
            this.usernameField.setText("没有此用户！！！");
            this.passwordField.setText("没有此用户！！！");

            Timer timer = new Timer(3000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    usernameField.setText("");
                    passwordField.setText("");
                }
            });
            timer.setRepeats(false);
            timer.start();

            return;
        }


        for (User user : users){
            if(ur.equals(user.getUsername()) && pass.equals(user.getPassword())){
                //关闭此界面
                this.setVisible(false);
                //跳转至主界面
                HomePage homePage = new HomePage();
            }

        }

            this.usernameField.setText("用户或密码错误！");
            this.passwordField.setText("用户或密码错误！");

        Timer timer = new Timer(3000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                usernameField.setText("");
                passwordField.setText("");
            }
        });
        timer.setRepeats(false);
        timer.start();

    }

    /**
     * 注册
     *
     * @param e
     */
    private void registerButtonMouseClicked(MouseEvent e) {
        // TODO add your code here

        System.out.println("注册按钮被点击");

        //获取文本框的内容
        String usernameText = this.usernameField.getText();
        String passwordText = this.passwordField.getText();

        if(usernameText.equals("用户密码不能为空！") || passwordText.equals("用户密码不能为空！")){
            return;
        }

        //判断文本框是否为空
        if(usernameText.isEmpty() || passwordText.isEmpty()){
            this.usernameField.setText("用户密码不能为空！");
            this.passwordField.setText("用户密码不能为空！");

            // 使用Swing定时器实现文本框提示信息自动清除
            Timer timer = new Timer(3000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    usernameField.setText("");
                    passwordField.setText("");
                }
            });
            timer.setRepeats(false);
            timer.start();


            return;
        }

        //将用户信息加入User实体类
        User user = new User(usernameText,passwordText);

        //TODO:来判断输入的格式是否正确


        //链接数据库
        Connection connection = JdbcConnectionUtils.getConnection();
        PreparedStatement statement = null;
        try {
            String sql = "insert into ww_user(username,password) values(?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,user.getUsername());
            statement.setString(2,user.getPassword());

            int i = statement.executeUpdate();

            if(i != 0){
                System.out.println("注册成功");

                //关闭此界面
                this.setVisible(false);
                //跳转至主界面
                HomePage homePage = new HomePage();


            }

        } catch (SQLException throwables) {
            throwables.getMessage();
        }finally {
            JdbcConnectionUtils.closeConnection(connection,statement,null);
        }


    }

    /**
     * 界面组件
     */
    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        title = new JLabel();
        username = new JLabel();
        password = new JLabel();
        usernameField = new JTextField();
        passwordField = new JPasswordField();
        loginButton = new JButton();
        registerButton = new JButton();

        //======== this ========
//        setBackground(new Color(0x00cccc));
        Container contentPane = getContentPane();

        //---- title ----
        title.setText("\u804c\u5de5\u5de5\u8d44\u7ba1\u7406\u7cfb\u7edf");
        title.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 30));

        //---- username ----
        username.setText("\u7528\u6237\u540d\uff1a");
        username.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 24));

        //---- password ----
        password.setText("  \u5bc6\u7801\uff1a");
        password.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 24));

        //---- usernameField ----
        usernameField.setForeground(new Color(0x2b2b30));

        //---- loginButton ----
        loginButton.setText("\u767b\u5f55");
        loginButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 20));
        loginButton.setBackground(Color.cyan);
        loginButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                loginButtonMouseClicked(e);
            }
        });

        //---- registerButton ----
        registerButton.setText("\u6ce8\u518c");
        registerButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 20));
        registerButton.setBackground(Color.cyan);
        registerButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                registerButtonMouseClicked(e);
            }
        });

        GroupLayout contentPaneLayout = new GroupLayout(contentPane);
        contentPane.setLayout(contentPaneLayout);
        contentPaneLayout.setHorizontalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(contentPaneLayout.createSequentialGroup()
                    .addGap(153, 153, 153)
                    .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                        .addGroup(contentPaneLayout.createSequentialGroup()
                            .addComponent(password, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(passwordField))
                        .addGroup(contentPaneLayout.createSequentialGroup()
                            .addComponent(username)
                            .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(contentPaneLayout.createParallelGroup()
                                .addComponent(title, GroupLayout.PREFERRED_SIZE, 249, GroupLayout.PREFERRED_SIZE)
                                .addComponent(usernameField, GroupLayout.PREFERRED_SIZE, 254, GroupLayout.PREFERRED_SIZE)))
                        .addGroup(contentPaneLayout.createSequentialGroup()
                            .addGap(58, 58, 58)
                            .addComponent(loginButton, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE)
                            .addGap(82, 82, 82)
                            .addComponent(registerButton, GroupLayout.PREFERRED_SIZE, 105, GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(224, Short.MAX_VALUE))
        );
        contentPaneLayout.setVerticalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(contentPaneLayout.createSequentialGroup()
                    .addGap(65, 65, 65)
                    .addComponent(title, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)
                    .addGap(72, 72, 72)
                    .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(username, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE)
                        .addComponent(usernameField, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE))
                    .addGap(53, 53, 53)
                    .addGroup(contentPaneLayout.createParallelGroup()
                        .addComponent(password, GroupLayout.PREFERRED_SIZE, 43, GroupLayout.PREFERRED_SIZE)
                        .addComponent(passwordField))
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
                    .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(loginButton, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE)
                        .addComponent(registerButton, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(45, Short.MAX_VALUE))
        );
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }


    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel title;
    private JLabel username;
    private JLabel password;
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}
